package com.platform.usercenter.teamfc.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.platform.common.core.domain.R;
import com.platform.common.core.domain.entity.ImUser;
import com.platform.common.core.domain.entity.SysDept;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.domain.model.LoginUser;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.UUIDUtils;
import com.platform.common.core.web.controller.BaseController;
import com.platform.common.core.web.domain.AjaxResult;
import com.platform.common.redis.service.RedisService;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.constants.SysUserConstants;
import com.platform.system.api.remote.api.RemoteSystemService;
import com.platform.usercenter.domain.*;
import com.platform.usercenter.domain.dto.*;
import com.platform.usercenter.domain.request.GetUserRoleFunctionRequest;
import com.platform.usercenter.domain.vo.*;
import com.platform.usercenter.mapper.SysDeptPostMapper;
import com.platform.usercenter.mapper.SysOrgDeptUserMapper;
import com.platform.usercenter.mapper.SysUserMapper;
import com.platform.usercenter.service.*;
import com.platform.usercenter.teamfc.domain.vo.PostIdAndDeptTypeVo;
import com.platform.usercenter.teamfc.service.PlatUserCenterFcService;
import com.platform.usercenter.utils.EmptyUtil;
import com.platform.usercenter.utils.HashCodeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: 可乐
 * @Description: 远程调用controller
 * @CreateTime: 2023-09-16  11:31
 */
@RestController
@RequestMapping("userCenterFc")
public class RemoteController extends BaseController {
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private RedisService redisService;
    @Resource
    private RemoteSystemService remoteSystemService;
    @Resource
    private ICalTeamService calTeamService;
    @Resource
    private ICalTeamMemberService calTeamMemberService;
    @Resource
    private IContactFrequentService contactFrequentService;
    @Resource
    private ISysDeptTaxService sysDeptTaxService;
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private PlatUserCenterFcService platUserCenterFcService;
    @Resource
    private ISysUserGuestService sysUserGuestService;
    @Resource
    private ISysOrganizationService organizationService;
    @Resource
    private SysDeptPostMapper sysDeptPostMapper;
    @Resource
    private ISysOrganizationService sysOrganizationService;
    @Resource
    private ISysUserService sysUserService;

    @Resource
    private SysOrgDeptUserMapper sysOrgDeptUserMapper;

    @Resource
    private ISysOrganizationDeptService organizationDeptService;

    /**
     * 绑定手表
     */
    @PostMapping("bindWatch")
    public R<LoginUser> bindWatch(@RequestBody SysUser sysUser) {
        remoteUserService.bindWatch(sysUser);
        return R.ok();
    }

    /**
     * 解绑手表
     */
    @PostMapping("unBindWatch")
    public R<LoginUser> unBindWatch(@RequestBody SysUser sysUser) {
        remoteUserService.unBindWatch(sysUser);
        return R.ok();
    }

    /**
     * 绑定VR眼镜
     */
    @PostMapping("bindVR")
    public R<LoginUser> bindVR(@RequestBody SysUser sysUser) {
        remoteUserService.bindVR(sysUser);
        return R.ok();
    }

    /**
     * 解绑手表
     */
    @PostMapping("unBindVR")
    public R<LoginUser> unBindVR(@RequestBody SysUser sysUser) {
        remoteUserService.unBindVR(sysUser);
        return R.ok();
    }

    /**
     * 获取二维码的信息
     */
    @GetMapping("/codeInfo")
    public R<String> getCodeInfo() {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        CodeInfo codeInfo = new CodeInfo();
        BeanUtils.copyProperties(sysUser, codeInfo);
        //生成一个UUID用于存储用户秘钥
        String codeKey = UUIDUtils.getGuid();
        redisService.setCacheObject(codeKey, codeInfo, 3L, TimeUnit.MINUTES);
        return R.ok(codeKey);
    }


    /**
     * 根据codeKey获取用户信息
     */
    @PostMapping("/getUserInfoByCode")
    public R<CodeInfo> getUserInfoByCode(String keyCode) {
        if (StringUtils.isEmpty(keyCode)) {
            return R.fail("秘钥不能为空!");
        }
        logger.info("获取到的秘钥------->" + keyCode);
        CodeInfo codeInfo = redisService.getCacheObject(keyCode);
        redisService.deleteObject(keyCode);
        return R.ok(codeInfo);
    }

    /**
     * 轮询检查二维码状态
     */
    @GetMapping("/checkCodeInfo")
    public R<Boolean> checkCodeInfo(String uuid) {
        if (StringUtils.isEmpty(uuid)) {
            return R.fail("参数缺失！");
        }
        Object cacheObject = redisService.getCacheObject(uuid);
        return R.ok(ObjectUtils.isEmpty(cacheObject));
    }

    /**
     * 根据用户类型/部门id查询用户信息
     */
    @PostMapping("/getUserByDeptType")
    public R<List<SysUser>> getUserByDeptType(@RequestBody SysUserVO sysUserVo) {
        List<SysUser> list = remoteUserService.getUserByDeptType(sysUserVo);
        return R.ok(list);
    }

    /**
     * 根据用户类型/部门id查询用户信息
     */
    @PostMapping("/getAllTeam")
    public R<List<CalTeam>> getAllTeam(@RequestBody CalTeam calTeam) {
        List<CalTeam> list = remoteUserService.getAllTeam(calTeam);
        return R.ok(list);
    }

    /**
     * 根据班组编号查询班组详情，和班组成员
     */
    @PostMapping("queryClaTeamUserByJobTyp")
    public R<List<CalTeamDetailDTO>> queryClaTeamUserByJobTyp(@RequestBody QueryClaTeamUserByJobTypeVO queryClaTeamUserByJobTypeVO) {
        if (!CollectionUtils.isNotEmpty(queryClaTeamUserByJobTypeVO.getJobType())) {
            return R.fail("必要参数缺失！");
        }
        List<CalTeamDetailDTO> calTeamDetailDTOS = new ArrayList<>();
        List<String> jobType = queryClaTeamUserByJobTypeVO.getJobType();
        List<CalTeam> calTeams = remoteUserService.selectCalTeams(jobType);
        for (CalTeam calTeam : calTeams) {
            CalTeamDetailDTO calTeamDetailDTO = new CalTeamDetailDTO();
            BeanUtils.copyProperties(calTeam, calTeamDetailDTO);
            CalTeamMember calTeamMember = new CalTeamMember();
            calTeamMember.setTeamId(calTeam.getTeamId());
            List<CalTeamMember> calTeamMembers = calTeamMemberService.selectCalTeamMemberList(calTeamMember);
            calTeamDetailDTO.setTeamMembers(calTeamMembers);
            calTeamDetailDTOS.add(calTeamDetailDTO);
        }
        return R.ok(calTeamDetailDTOS);
    }


    /**
     * 手边端获取常用联系人
     */
    @PostMapping("/contactFrequentList")
    public R<List<ContactFrequent>> contactFrequentList(@RequestBody ContactFrequent contactFrequent) {
        //查询登录用户拥有的contactId集合
        Long userId = contactFrequent.getUserId();
        ContactVo contactVo = new ContactVo();
        contactVo.setRelationUserId(userId);
        List<ContactFrequent> list = contactFrequentService.selectContactFrequentListByContact(contactVo);
        for (ContactFrequent frequent : list) {
            SysUser user = userService.selectUserById(frequent.getUserId());
            if (StringUtils.isNotEmpty(user.getAvatar())) {
                frequent.setAvatar(user.getAvatar());
            }
        }
        return R.ok(list);
    }

    /**
     * 根据用户岗位和类型获取UOC的用户信息
     */
    @PostMapping("/getUserByPostIdAndDeptType")
    public R<List<SysUser>> contactFrequentList(@RequestBody PostIdAndDeptTypeVo postIdAndDeptTypeVo) {
        List<SysUser> list = remoteUserService.getUserByPostIdAndDeptType(postIdAndDeptTypeVo);
        return R.ok(list);
    }

    /**
     * 获取部门税号
     */
    @PostMapping("/getTaxInfo")
    public R<List<TaxInfoDTO>> getTaxInfo(@RequestBody TaxInfoVO taxInfoQueryVO) {
        logger.info("getTaxInfo query params is :{}", JSON.toJSONString(taxInfoQueryVO));
        // 查询税号数据
        List<SysDeptTax> sysDeptTaxes = sysDeptTaxService.selectSysDeptTaxList(new SysDeptTax());
        List<TaxInfoDTO> taxInfoDTOList = sysDeptTaxes.stream().map(item -> {
            // TODO 后续改造
            SysDept sysDept = sysDeptService.selectDeptById(item.getDeptId());
            TaxInfoDTO taxInfoDTO = new TaxInfoDTO();
            taxInfoDTO.setDeptId(String.valueOf(item.getDeptId()));
            if (Objects.nonNull(sysDept)) {
                taxInfoDTO.setDeptName(sysDept.getDeptName());
                taxInfoDTO.setSalerTaxName(sysDept.getDeptName());
            }
            taxInfoDTO.setTaxCode(item.getTaxId());
            return taxInfoDTO;
        }).collect(Collectors.toList());
        return R.ok(taxInfoDTOList);
    }

    @RequestMapping("/getImPwd")
    public R<ImUser> getImPwd() {
        String userName = SecurityUtils.getUsername();
        logger.info("******userName:{}", userName);
        ImUser user = sysUserMapper.selectSysUserPwdByUserName(userName);
        int impwd = HashCodeUtil.getHashCode(user.getPwd());
        user.setPwd("");
        user.setImPwd(impwd);
        return R.ok(user);
    }

    @PostMapping("/getUserListInfo")
    public R<List<SysUser>> getUserListInfo(@RequestBody Long[] userIds) {
        List<SysUser> list = platUserCenterFcService.getUserListInfo(userIds);
        return R.ok(list);
    }

    @PostMapping("/getUserListByIds")
    public R<List<SysUser>> getUserListByIds(@RequestParam("userIds") Long[] userIds) {
        List<SysUser> list = platUserCenterFcService.getUserListInfo(userIds);
        return R.ok(list);
    }

    @RequestMapping("/getImPwdByUserName")
    public R<ImUser> getImPwdByUserId(@RequestBody SysUser sysUser) {
        logger.info("******userName:{}", sysUser.getUserName());
        ImUser user = new ImUser();
        int impwd = HashCodeUtil.getHashCode(sysUser.getPassword());
        user.setPwd("");
        user.setImPwd(impwd);
        return R.ok(user);
    }

    /**
     * 获取游客登录信息
     */
    @PostMapping("/getGuestInfo")
    public R<List<SysUserGuest>> getGuestInfo(@RequestBody SysUserGuest userGuest) {
        return R.ok(sysUserGuestService.selectSysUserGuestList(userGuest));
    }

    /**
     * 新增游客登录信息
     */
    @PostMapping("/addUserGuest")
    public R<Long> addUserGuest(@RequestBody SysUserGuest userGuest) {
        int rows = sysUserGuestService.insertSysUserGuest(userGuest);
        if (rows > 0) {
            return R.ok(userGuest.getUserId());
        } else {
            return R.fail();
        }
    }

    /**
     * 修改游客登录信息
     */
    @PostMapping("/editUserGuest")
    public R<Integer> editUserGuest(@RequestBody SysUserGuest userGuest) {
        return R.ok(sysUserGuestService.updateSysUserGuest(userGuest));
    }

    /**
     * 根据orgId获取组织信息
     */
    @GetMapping("/selectByOrgId/{orgId}")
    public R<SysOrganization> selectByOrgId(@PathVariable Long orgId) {
        return R.ok(organizationService.selectSysOrganizationByOrgId(orgId));
    }

    /**
     * 获取当前用户关联组织下的部门信息
     */
    @GetMapping("/selectUserOrgIdPost")
    public R<List<SysDeptPost>> selectUserOrgIdPost() {
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        Long userid = SecurityUtils.getLoginUser().getUserid();
        List<SysDeptPost> sysDeptPosts = new ArrayList<>();
        if (!Objects.isNull(orgId)) {
            SysDeptPost deptPostQuery = new SysDeptPost();
            deptPostQuery.setOrgId(orgId);
            deptPostQuery.setUserId(userid);
            deptPostQuery.setIsDelete(SysUserConstants.N);
            sysDeptPosts = sysDeptPostMapper.selectSysDeptPostList(deptPostQuery);
        }
        return R.ok(sysDeptPosts);
    }

    /**
     * 获取所有岗位信息
     */
    @GetMapping("/selectAllOrgIdPost")
    public R<List<SysDeptPost>> selectAllOrgIdPost() {
        SysDeptPost deptPostQuery = new SysDeptPost();
        deptPostQuery.setIsDelete(SysUserConstants.N);
        return R.ok(sysDeptPostMapper.selectSysDeptPostList(deptPostQuery));
    }

    /**
     * 获取当前账号所有岗位信息
     */
    @GetMapping("/getCurrentUserOrgPost")
    public R<List<SysDeptPost>> getCurrentUserOrgPost() {
        SysDeptPost deptPostQuery = new SysDeptPost();
        deptPostQuery.setIsDelete(SysUserConstants.N);
        deptPostQuery.setUserId(SecurityUtils.getLoginUser().getUserid());
        return R.ok(sysDeptPostMapper.selectSysDeptPostList(deptPostQuery));
    }

    /**
     * 获取当前用户拥有权限的组织
     */
    @GetMapping("/selectUpAndDownOrgs")
    public R<List<SysOrganizationRelation>> selectUpAndDownOrgs() {
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        Set<Long> orgIdSet = new HashSet<>();
        orgIdSet.add(orgId);
        SysOrganizationVO sysOrganizationVO = sysOrganizationService.listTreeByUserOrg(new SysOrganization(), orgId);
        ArrayList<SysOrganizationVO> sysOrganizationVOs = new ArrayList<>();
        sysOrganizationVOs.add(sysOrganizationVO);
        if (!EmptyUtil.isHaveEmpty(sysOrganizationVO)) {
            Stream<SysOrganizationVO> allEntitiesStream = sysOrganizationVOs.stream()
                    .flatMap(entity -> Stream.concat(
                            Stream.of(entity),
                            Stream.of(entity.getChildren()).flatMap(List::stream) // 展开第一层子节点
                    ));
            orgIdSet = allEntitiesStream
                    .map(SysOrganizationVO::getOrgId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());
        }
        return R.ok(sysOrganizationService.selectUpAndDownOrgsByParentOrgIds(orgIdSet));
    }

    /**
     * 获取当前用户拥有权限的组织
     */
    @GetMapping("/selectRealDownOrgs")
    public R<List<SysOrganizationVO>> selectRealDownOrgs() {
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        List<SysOrganizationVO> sysOrganizationVOS = new ArrayList<>();

        SysOrganizationVO sysOrganizationVO = sysOrganizationService.listTreeByUserOrg(new SysOrganization(), orgId);
        if (!EmptyUtil.isHaveEmpty(sysOrganizationVO)) {
            sysOrganizationVOS.add(sysOrganizationVO);
        }
        return R.ok(sysOrganizationVOS);
    }

    /**
     * 组织树结构查询
     */
    @GetMapping("/listTree")
    public AjaxResult listTree(SysOrganization sysOrganization) {
        return AjaxResult.success(sysOrganizationService.listTree(sysOrganization));
    }

    /**
     * 组织树结构查询
     */
    @PostMapping("/listOrgTree")
    public R<List<SysOrganizationVO>> listOrgTree(@RequestBody SysOrganization sysOrganization) {
        return R.ok(sysOrganizationService.listOrgTree(sysOrganization));
    }


    /**
     * 根据userId+orgId
     * 1，获取部门列表及其子级部门列表
     * 2，获取当前组织的全部下级列表
     */
    @PostMapping("/getUserInfoList")
    public R<SysUserDetailDTO> getUserInfoList(@RequestParam("userId") Long userId, @RequestParam("orgId") Long orgId) {
        SysUserDetailDTO infoDTO = new SysUserDetailDTO();
        // 获取用户部门列表
        List<SysUserDeptDTO> deptList = new ArrayList<>();
        List<Long> allOrgIds = new ArrayList<>();
        List<Long> allDeptIds = new ArrayList<>();
        SysOrgDeptUser userDeptQuery = new SysOrgDeptUser();
        userDeptQuery.setIsDelete(SysUserConstants.N);
        userDeptQuery.setUserId(userId);
        userDeptQuery.setOrgId(orgId);
        List<SysOrgDeptUser> userDeptList = sysOrgDeptUserMapper.selectSysOrgDeptUserList(userDeptQuery);
        if (CollectionUtil.isNotEmpty(userDeptList)) {
            for (SysOrgDeptUser vo : userDeptList) {
                if (ObjectUtils.isEmpty(vo.getDeptId())) {
                    continue;
                }
                SysUserDeptDTO deptDTO = new SysUserDeptDTO();
                deptDTO.setDeptId(vo.getDeptId());
                List<Long> childrenDeptIds = sysOrgDeptUserMapper.selectChildrenDeptIds(vo.getDeptId());
                if (CollectionUtil.isNotEmpty(childrenDeptIds)) {
                    deptDTO.setChildrenDeptIds(childrenDeptIds);
                    allDeptIds.addAll(childrenDeptIds);
                }
                deptList.add(deptDTO);
                allDeptIds.add(vo.getDeptId());
            }
            infoDTO.setDeptList(deptList);
        }
        // 获取组织下的全部子组织集合
        List<Long> childrenOrgIds = sysOrgDeptUserMapper.selectChildrenOrgIds(orgId);
        if (CollectionUtil.isNotEmpty(childrenOrgIds)) {
            infoDTO.setChildrenOrgIds(childrenOrgIds);
            allOrgIds.addAll(childrenOrgIds);
        }
        // 获取用户角色是否包含组织文件管理员
        List<String> roleTypes = sysOrgDeptUserMapper.selectUserRoleType(userId, orgId);
        if(CollectionUtil.isNotEmpty(roleTypes)){
            infoDTO.setAllRoleType(roleTypes);
            if(roleTypes.contains("ORG_FILE_ADMINISTRATOR")||roleTypes.contains("ORG_FILE_AUDITOR")||roleTypes.contains("OUTER_FILE_ADMINISTRATOR")){
                infoDTO.setRoleType("ORG");
            } else {
                infoDTO.setRoleType("DEPT");
            }
        }
        infoDTO.setAllDepts(allDeptIds);
        allOrgIds.add(orgId);
        infoDTO.setAllOrgIds(allOrgIds);
        return R.ok(infoDTO);
    }


    /**
     * 获取部门列表
     *
     * @param dept
     * @return
     */
    @PostMapping("/getDeptList")
    public R<List<SysOrganizationDept>> getDeptList(@RequestBody SysOrganizationDept dept) {
        List<SysOrganizationDept> deptList = organizationDeptService.selectSysOrganizationDeptList(dept);
        return R.ok(deptList);
    }

    /**
     * 获取组织列表
     *
     * @param organization
     * @return
     */
    @PostMapping("/getOrgList")
    public R<List<SysOrganization>> getOrgList(@RequestBody SysOrganization organization) {
        List<SysOrganization> list = sysOrganizationService.selectSysOrganizationList(organization);
        return R.ok(list);
    }

    /**
     * 获取当前组织下的直属部门
     *
     * @param organization
     * @return
     */
    @PostMapping("/getDirectlyOrgDeptList")
    public R<List<SysOrganizationDept>> getDirectlyOrgDeptList(@RequestBody SysOrganization organization) {
        SysOrganizationDept dept = new SysOrganizationDept();
        dept.setParentId(0L);
        dept.setOrgId(organization.getOrgId());
        List<SysOrganizationDept> deptList = organizationDeptService.selectSysOrganizationDeptList(dept);
        return R.ok(deptList);
    }

    /**
     * 获取当前部门下的直属部门
     *
     * @param organizationDept
     * @return
     */
    @PostMapping("/getDirectlyDeptList")
    public R<List<SysOrganizationDept>> getDirectlyDeptList(@RequestBody SysOrganizationDept organizationDept) {
        organizationDept.setParentId(organizationDept.getDeptId());
        List<SysOrganizationDept> deptList = organizationDeptService.selectSysOrganizationDeptList(organizationDept);
        return R.ok(deptList);
    }


    /**
     * 根据用户体系主体数据交换用户ID列表
     *
     * @param userSubjectDTO 用户体系主体数据
     * @return 用户ID列表
     */
    @PostMapping("/exchangeUserIdBySubject")
    public R<List<String>> exchangeUserIdBySubject(@RequestBody UserSubjectDTO userSubjectDTO) {
        List<String> res = sysUserService.exchangeUserIdBySubject(userSubjectDTO);
        return R.ok(res);
    }

    /**
     * 获取用户角色职能
     *
     * @param request 请求数据
     * @return 角色职能列表
     */
    @PostMapping("/getUserRoleFunction")
    public R<List<String>> getUserRoleFunction(@RequestBody GetUserRoleFunctionRequest request) {
        List<String> res = sysUserService.getUserRoleFunction(request);
        return R.ok(res);
    }
}
